package com.goa.parse;

public class ModbusCRC16 {

   /* public static void main(String[] args) {
        byte[] bytes ={-50, -46, -80, -82, -60, -29, 49,49};
        String crc = getCRC(bytes);
        System.out.println("crc = " + crc);
    }*/

    public static String getCRC(byte[] bytes) {
        int CRC = 0x0000ffff;
        int POLYNOMIAL = 0x0000a001;

        int i, j;
        for (i = 0; i < bytes.length; i++) {
            CRC ^= ((int) bytes[i] & 0x000000ff);
            for (j = 0; j < 8; j++) {
                if ((CRC & 0x00000001) != 0) {
                    CRC >>= 1;
                    CRC ^= POLYNOMIAL;
                } else {
                    CRC >>= 1;
                }
            }
        }
        CRC = (( (CRC & 0xFF00) >> 8) | ( (CRC & 0x00FF ) << 8));
        return Integer.toHexString(CRC);
    }

    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i+1), 16));
        }
        return data;
    }

    public static String getCRC16(String s){
        byte[] byteArray = hexStringToByteArray(s);
        return getCRC(byteArray);
    }
}
